package cn.lotusnut.rabbitmqbaseapi.mq.simplest;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @Author JiangMing Zhou
 * @Date 2022/11/30 22:03
 * @Version 1.8
 */
public class AckConsume {

    public static void main(String[] args) throws IOException, TimeoutException {
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("47.108.157.114");
        connectionFactory.setVirtualHost("/");
        connectionFactory.setPort(5672);
        connectionFactory.setUsername("guest");
        connectionFactory.setPassword("511923ZjM5219");
        Connection connection = connectionFactory.newConnection();
        Channel channel = connection.createChannel();
        channel.queueDeclare("queuesimplest", true, false, false, null);
        channel.basicConsume("queuesimplest", false, new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                try {
                    System.out.println("consumerTag：" + consumerTag);
                    System.out.println("envelope：" + envelope);
                    System.out.println("properties：" + properties);
                    System.out.println("body：" + new String(body));
                    channel.basicAck(envelope.getDeliveryTag(), false);
                }catch (Exception e){
                    //消息ID，是否批量拒绝，是否放回队列
                    channel.basicNack(envelope.getDeliveryTag(),false,true);
                }


            }
        });
    }
}
